/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JCP;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 *
 * @author Pham
 */
public final class UIBrower implements Browser {

    public JFrame frame;
    public JPanel panelTop;
    public JMenuBar menuTop;
    public ArrayList<JMenu> menuList;
    public JPanel editor;
    public JScrollPane scroll;
    public JTextField field;
    public JButton buttongo;
    public JButton buttonback;
    public JButton buttonnext;
    public JButton buttontool;
    public URL url;
    public String urlparameter;
    public String classname;
    public String parametervalue1;
    public String parametervalue2;
    public ArrayList<String> urlaccesed = new ArrayList<>();
    public int count = 0;
    public HashMap<String, String> parameters;

    public UIBrower() {
        initComponents();
        frame.setTitle("Java Client Page");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1800, 1030);
        frame.add(BorderLayout.PAGE_START, panelTop);
        frame.add(BorderLayout.PAGE_END, menuTop);
        panelTop.add(buttonback);
        panelTop.add(buttonnext);
        panelTop.add(field);
        panelTop.add(buttongo);
        panelTop.add(buttontool);
        frame.add(BorderLayout.CENTER, scroll);
        frame.setVisible(true);
    }

    public void initComponents() {
        //create the JFrame
        frame = new JFrame();
        panelTop = new JPanel();
        try {
            url = new URL("http://localhost/");
        } catch (MalformedURLException mue) {
            JOptionPane.showMessageDialog(null, mue);
        }

        editor = new JPanel();
        menuTop = new JMenuBar();



        //JMenu home = new JMenu("Start");
        // setMenu(home);
        scroll = new JScrollPane(editor, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        field = new JTextField();
        field.setPreferredSize(new Dimension(400, 27));

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                field.setText(url.toString());
            }
        });

        //ImageIcon image = new ImageIcon("images.jpg");

        buttonnext = new JButton("Next");
        buttonnext.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (count < urlaccesed.size()) {
                    go(urlaccesed.get(count));

                }
            }
        });

        buttonback = new JButton("Back");
        buttonback.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (count >= 2) {
                    count = count - 2;
                    go(urlaccesed.get(count));
                    //  System.out.println(urlaccesed.get(count));
                }
            }
        });



        buttontool = new JButton("Tool");
        buttontool.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Java Client Page Version 0.1", "About", JOptionPane.PLAIN_MESSAGE);
            }
        });






        //  buttontool = new JButton(new ImageIcon(((new ImageIcon("tool.png").getImage()
        //        .getScaledInstance(20, 20, java.awt.Image.SCALE_DEFAULT)))));
        //button = new JButton(image);
        //buttongo = new JButton(new ImageIcon(((new ImageIcon(
        //  "images.jpg").getImage()
        // .getScaledInstance(20, 30,
        //     java.awt.Image.SCALE_DEFAULT)))));
        buttongo = new JButton("GO");
        buttongo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                urlparameter = field.getText();
                //  try {
                go(urlparameter);

            }
        });
    }

    @Override
    public void setMenu(ArrayList<JMenu> jm) {
        menuList = new ArrayList<>();
        menuList = jm;
        menuTop.removeAll();
        for (int i = 0; i < menuList.size(); i++) {

            menuTop.add(menuList.get(i));
            menuTop.updateUI();

        }



    }

    @Override
    public void go(String urlparameter) {
        try {
            urlaccesed.add(urlparameter);
            count++;
            //  System.out.println(count);
            HashMap<String, Object> parameters = new HashMap<String, Object>();
            if (!urlparameter.equals(url.toString())) {
                if (urlparameter.contains("http://localhost/") && urlparameter.contains("?")) {
                    String classn = urlparameter.substring(urlparameter.indexOf("?", 0));
                    String classn2 = urlparameter.replaceAll("http://localhost/", "");
                    classname = classn2.replace(classn, "");

                    if (urlparameter.contains("&")) {
                        String para2 = urlparameter.substring(urlparameter.indexOf("&", 0));
                        parametervalue2 = para2.replaceAll("&", "");
                        String para1 = urlparameter.substring(urlparameter.indexOf("?", 0));
                        String para12 = para1.replaceAll(para2, "");
                        parametervalue1 = para12.substring(1, para12.length());
                        URLClassLoader loader;
                        loader = new URLClassLoader(new URL[]{new URL("http://localhost/")});
                        Class c = loader.loadClass(classname);
                        Object o = c.newInstance();
                        String para1value = parametervalue1.substring(parametervalue1.indexOf("=", 0));
                        String para2value = parametervalue2.substring(parametervalue1.indexOf("=", 0));
                        parameters.put("name", para1value.replaceAll("=", ""));
                        parameters.put("city", para2value.replaceAll("=", ""));
                        JavaClientPage jcp = (JavaClientPage) o;
                        jcp.setParameters(parameters);
                        jcp.setBrowser(this);
                        editor.removeAll();
                        editor.add(jcp.getBody());
                        editor.updateUI();
                    }
                } else if (urlparameter.contains("http://localhost/") && !urlparameter.contains("?")) {
                    classname = urlparameter.replaceAll("http://localhost/", "");
                    URLClassLoader loader;
                    loader = new URLClassLoader(new URL[]{new URL("http://localhost/")});
                    Class c = loader.loadClass(classname);
                    Object o = c.newInstance();
                    JavaClientPage jcp = (JavaClientPage) o;
                    jcp.setParameters(parameters);
                    jcp.setBrowser(this);
                    editor.removeAll();
                    editor.add(jcp.getBody());
                    editor.updateUI();
                } else {
                    JLabel lberror = new JLabel("Sorry we can not find your page .Please try another page");
                    editor.removeAll();
                    editor.add(lberror);
                    editor.updateUI();
                }

            } else {
                JLabel lberror = new JLabel("Please enter your pages");
                editor.removeAll();
                editor.add(lberror);
                editor.updateUI();
            }


        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | MalformedURLException ex) {
            JLabel lberror = new JLabel("Sorry we can not find your page .Please try another page");
            editor.removeAll();
            editor.add(lberror);
            editor.updateUI();
        }
    }

    @Override
    public String localstorage(String keypara) {
        String connectst = "jdbc:sqlite:" + classname + ".db";
        // System.out.println(keypara);
       String rt = "";
        Connection c = null;
        Statement stmt = null;
        String crtable = "CREATE TABLE IF NOT EXISTS " + classname.toUpperCase() + " "
                + "(ID INTEGER PRIMARY KEY     AUTOINCREMENT NOT NULL,"
                + " KEY           TEXT   UNIQUE NOT NULL, "
                + " VALUE            TEXT     NOT NULL)";
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection(connectst);
            stmt = c.createStatement();
            stmt.executeUpdate(crtable);
            // stmt.executeUpdate(sql);
            ResultSet rs = stmt.executeQuery("SELECT * FROM " + classname.toUpperCase() + ";");
            if (rs.next()) {
                rs.close();
                ResultSet rs2 = stmt.executeQuery("SELECT * FROM " + classname.toUpperCase() + ";");
                // System.out.println("This is true");  
                while (rs2.next()) {
                   // int id = rs.getInt("id");
                    String key = rs2.getString("key");
                    String value = rs2.getString("value");
                    //System.out.println("ID = " + id);
                    //System.out.println("Key = " + key);
                    //System.out.println("Value = " + value);
                  //  System.out.println();
                    if (keypara.equals(key)) {
                        
                    //   System.out.println("This is a value " + value);
                       rt = value;

                    }
                    
                }
            } else {
                rt = "";
             // System.out.println("Khong co database");      
            }

            rs.close();
            stmt.close();
            c.close();
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        return rt;

    }

    /**
     *
     * @param localparameter
     */
    @Override
    public void localstorage(Map<String, String> localparameter) {
        String connectst = "jdbc:sqlite:" + classname + ".db";
        Set s = localparameter.entrySet();
        //Move next key and value of Map by iterator
        Iterator it = s.iterator();
        Connection c = null;
        Statement stmt = null;
        String crtable = "CREATE TABLE IF NOT EXISTS " + classname.toUpperCase() + " "
                + "(ID INTEGER PRIMARY KEY     AUTOINCREMENT NOT NULL,"
                + " KEY           TEXT   UNIQUE NOT NULL, "
                + " VALUE            TEXT     NOT NULL)";
        try {
            
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection(connectst);
            stmt = c.createStatement();
            stmt.executeUpdate(crtable);
            // stmt.executeUpdate(sql);
            while (it.hasNext()) {
                // key=value separator this by Map.Entry to get key and value
                Map.Entry m = (Map.Entry) it.next();

                // getKey is used to get key of Map
                String key = (String) m.getKey();

                // getValue is used to get value of key in Map
                String value = (String) m.getValue();

            //  System.out.println("Key :"+key+"  Value :"+value);
                String keyp = "'" + key + "'";

                String valuep = "'" + value + "'";

                String sql = "INSERT OR IGNORE  INTO  " + classname.toUpperCase() + "(ID,KEY,VALUE) "
                        + "VALUES (null," + keyp + "," + valuep + ");";
                 stmt.executeUpdate(sql);
                stmt.close(); 
                   
            } 
             c.close();  

        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
        //  System.out.println("Created database successfully");
    }
}
